package com.adc.douyu_assistant.client;

import com.adc.douyu_assistant.entity.DouyuMessage;
import com.adc.douyu_assistant.entity.DouyuMessageHeader;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class DouyuMessageDecoder extends ByteToMessageDecoder {
    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
        while (in.isReadable(12)) {
            int length_length = in.readIntLE();
            int header_length = in.readIntLE();
            short header_type = in.readShort();
            Byte header_encry = in.readByte();
            Byte header_remain = in.readByte();

            if (header_length != header_length || in.readableBytes() != header_length - 8) {
                in.readerIndex(in.readableBytes());
                return;
            }

            byte[] contentBytes = new byte[header_length - 8];
            in.readBytes(contentBytes);
            String content = new String(contentBytes);

            DouyuMessageHeader header = new DouyuMessageHeader(content.length(), header_type);
            DouyuMessage message = new DouyuMessage(header, content);

            out.add(message);
        }
    }
}

